package cn.androidstudy.listviewdemo;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

/**
 * Time: 2020/3/19
 * Author: wangzhiguo
 * Description: MyAdapter适配器的升级版，优化
 */
public class MyAdapterNew extends BaseAdapter {
    private Context context;//加载布局使用
    private List<AppBean> mApps;

    public MyAdapterNew(Context context, List<AppBean> mApps) {
        this.context = context;
        this.mApps = mApps;
    }

    @Override
    public int getCount() {//决定ListView中Item的数量
        return mApps.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

//    //为每个Item生成视图
//    @Override
//    public View getView(int position, View convertView, ViewGroup parent) {
//        //1.加载布局
//        View view= LayoutInflater.from(context)
//                .inflate(R.layout.list_item,parent,false);
//        //2.设置view中组件的属性
//        ImageView imageView=view.findViewById(R.id.imgtou);
//        TextView tvName=view.findViewById(R.id.name);
//        TextView tvSays=view.findViewById(R.id.says);
//        AppBean bean=mApps.get(position);
//        imageView.setImageResource(bean.getImgId());
//        tvName.setText(bean.getName());
//        tvSays.setText(bean.getDesc());
//        //3.返回view，将绘制到Item
//        return view;
//    }

    /**
     * 改进：1.重用convertView，存储加载的视图
     * 2.使用ViewHolder对象，存储查找的组件对象；
     * @param position
     * @param convertView
     * @param parent
     * @return
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder1 holder;//定义对象，存储查找的组件对象
        //判断是否为空，如为空，则为第一次加载
        if(convertView==null){
            //1.加载布局
            convertView= LayoutInflater.from(context)
                    .inflate(R.layout.list_item,parent,false);
            //2.使用holder存储view中组件
            holder=new ViewHolder1();
            holder.imageView=convertView.findViewById(R.id.imgtou);
            holder.tvName=convertView.findViewById(R.id.name);
            holder.tvDesc=convertView.findViewById(R.id.says);
            //3.存储holder到convertView，供下次重用
            convertView.setTag(holder);
        }else {//不是第一次，直接获取holder
            holder= (ViewHolder1) convertView.getTag();
        }

        AppBean bean=mApps.get(position);
        holder.imageView.setImageResource(bean.getImgId());
        holder.tvName.setText(bean.getName());
        holder.tvDesc.setText(bean.getDesc());
        //3.返回view，将绘制到Item
        return convertView;
    }
    //用来存储view中相应的组件
    class ViewHolder1{
        public TextView tvName;
        public TextView tvDesc;
        public ImageView imageView;
    }

}
